//
//  WBTitleButton.swift
//  Weibo
//
//  Created by niqiang on 16/7/11.
//  Copyright © 2016年 niqiang. All rights reserved.
//

import UIKit

class WBTitleButton: UIButton {
//重载构造函数
    //title如果是nil,就显示“首页" , 如果不是nil, 显示title 和箭头头像
    init(title: String?) {
    super.init(frame: CGRect())
        
        //1>判断title == nil
        if title == nil {
            setTitle("首页", for: [])
        }else{
        setTitle(title! + "", for: [])
            //设置图像
            setImage(UIImage(named: "navigationbar_arrow_down"), for: [])
            setImage(UIImage(named: "navigationbar_arrow_up"), for: .selected)
        }
        //2>设置字体和颜色
        titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
        setTitleColor(UIColor.darkGray(), for: [])
        
        //3> 设置大小
        sizeToFit()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //重新布局子控件
    override func layoutSubviews() {
        super.layoutSubviews()
        
        //判断label和 imageView是否同时存在
        guard let titleLabel = titleLabel, imageView = imageView else {
            return
        }
        print("\(titleLabel) \(imageView)")
        
        //将label的x向左移动 imageView 的宽度
        titleLabel.frame = titleLabel.frame.offsetBy(dx: -imageView.bounds.width, dy: 0)
        
        //将imageView 的x向右移动label 的宽度
        imageView.frame = imageView.frame.offsetBy(dx: titleLabel.bounds.width, dy: 0)
        
    }
}
